require 'settings'
require 'libglade2'

SETTINGSDIALOG_FILE = "settingsdialog.glade"
SETTINGSDIALOG_TITLE = "Rsgtk downloader settings"

class SettingsDialog
  
  attr :glade
  attr :dialog
  attr :settings
  
  attr :callback # object to call on_settings_changed
  
  def initialize(callback)
    
    @callback = callback;
    
    @glade = GladeXML.new(SETTINGSDIALOG_FILE, nil, SETTINGSDIALOG_TITLE, nil, GladeXML::FILE) { |handler| method(handler)}
    @dialog = @glade['settingsdialog']
    @dialog.show_all
    
    @settings = Settings.load
    
    @glade['settings_entry_username'].text = @settings.username
    @glade['settings_entry_password'].text = @settings.password
    @glade['settings_entry_maxconcur'].text = @settings.max_concurrent_downloads.to_s
    @glade['settings_entry_downloadloc'].text = @settings.download_location
  end
  
  def on_settings_closebutton_clicked
    
    @settings.username = @glade['settings_entry_username'].text
    @settings.password = @glade['settings_entry_password'].text
    if numeric? @glade['settings_entry_maxconcur'].text
      @settings.max_concurrent_downloads =  @glade['settings_entry_maxconcur'].text
    end
    @settings.download_location = @glade['settings_entry_downloadloc'].text
    @settings.save
    @dialog.destroy
    
    if @callback.respond_to?("on_settings_changed")
      @callback.on_settings_changed(@settings)
    end
  end
  
  def numeric?(object)
     true if Float(object) rescue false
  end
  
end
